package com.jshoperxms.controller.api.langdu;

import com.jshoperxms.Response;
import com.jshoperxms.controller.mall.backstage.base.BaseTController;
import com.jshoperxms.controller.utils.DateTools;
import com.jshoperxms.controller.utils.PrimaryKey;
import com.jshoperxms.controller.utils.enums.BaseEnums;
import com.jshoperxms.controller.utils.statickey.StaticKey;
import com.jshoperxms.controller.utils.statickey.TagWords;
import com.jshoperxms.controller.utils.statickey.WarnWrods;
import com.jshoperxms.entity.*;
import com.jshoperxms.service.*;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.lang.reflect.Member;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by sdywcd on 2018/9/30.
 * Des:
 */
@RestController
@RequestMapping("/api/member")
public class MemberController extends BaseTController {


    @Resource
    private MemberTService memberTService;

    @Resource
    private MemberGradeRpTService memberGradeRpTService;

    @Resource
    private MemberGradeTService memberGradeTService;

    @Resource
    private YdStatusInfoTSerivce ydStatusInfoTSerivce;

    @Resource
    private YdTreeInfoTService ydTreeInfoTService;

    @Resource
    private SysMsgRpTService sysMsgRpTService;

    @Resource
    private SysMsgcontentTService sysMsgcontentTService;

    @Resource
    private YdRecordRdTService ydRecordRdTService;



    @RequestMapping(value="/updateRecordsNickAndHeadPath",method= RequestMethod.POST)
    public ResponseEntity updateRecordsNickAndHeadPath(){
        Map<String,Object> responsedata=new HashMap<>();
        int chagne=0;
        List<MemberT>memberTList=this.memberTService.findAll(MemberT.class);
        for(MemberT memberT:memberTList){
            Criterion criterion=Restrictions.eq("wxopenid",memberT.getWxopenid());
            List<YdRecordRdT>list=this.ydRecordRdTService.findByCriteria(YdRecordRdT.class,criterion);
            if(!list.isEmpty()){
                chagne++;
                for(YdRecordRdT ydRecordRdT:list){
                    ydRecordRdT.setAuthorheadimg(memberT.getHeadpath());
                    ydRecordRdT.setAuthornick(memberT.getNick());
                }
            }

        }
        responsedata.put("change",chagne);
        return Response.success(responsedata);
    }

    @RequestMapping(value="/calMemberGrade",method= RequestMethod.POST)
    public ResponseEntity setMemberGrades(){
        //查询status表
        Map<String,Object> responsedata=new HashMap<>();
        List<YdStatusInfoT>list=this.ydStatusInfoTSerivce.findAll(YdStatusInfoT.class);
        for(YdStatusInfoT ydStatusInfoT:list){
            responsedata.put(ydStatusInfoT.getMemberid(),compareLevel(ydStatusInfoT.getTotalleafs()));
        }
        //便利map更新数据库
        for (Map.Entry<String, Object> entry : responsedata.entrySet()) {
            //Map.entry<Integer,String> 映射项（键-值对）  有几个方法：用上面的名字entry
            //entry.getKey() ;entry.getValue(); entry.setValue();
            //map.entrySet()  返回此映射中包含的映射关系的 Set视图。
            System.out.println("key= " + entry.getKey() + " and value= "
                    + entry.getValue());
            Criterion criterion=Restrictions.eq("memberid",entry.getKey());

            MemberGradeRpT memberGradeRpT=this.memberGradeRpTService.findOneByCriteria(MemberGradeRpT.class,criterion);
            if(memberGradeRpT!=null){
                memberGradeRpT.setCurrentlevel(Integer.parseInt(entry.getValue().toString()));
                memberGradeRpT.setUpdatetime(DateTools.getSystemTimeLong());
                memberGradeRpT.setVersiont(memberGradeRpT.getVersiont()+1);
                this.memberGradeRpTService.update(memberGradeRpT);

                Criterion criterion1=Restrictions.eq("levelname",Integer.parseInt(entry.getValue().toString()));
                MemberGradeT memberGradeT=this.memberGradeTService.findOneByCriteria(MemberGradeT.class,criterion1);
                if(memberGradeT!=null) {
                    memberGradeRpT.setMembergradeid(memberGradeT.getId());
                    this.memberGradeRpTService.update(memberGradeRpT);
                    //发送消息到个人消息中心中
                    SysMsgcontentT bean=new SysMsgcontentT();
                    bean.setId(PrimaryKey.get().toString());
                    bean.setMsgcontent("系统通知您，您的当前朗读等级是Lv"+memberGradeRpT.getCurrentlevel());
                    this.sysMsgcontentTService.save(bean);
                    SysMsgRpT b=new SysMsgRpT();
                    b.setId(PrimaryKey.get().toString());
                    b.setMsgcontentid(bean.getId());
                    b.setReadtime(DateTools.getSystemTimeLong());
                    b.setSenderid("0");//0表示系统
                    b.setReceiverid(memberGradeRpT.getMemberid());
                    b.setReadstatus("1");
                    b.setTitle("");
                    b.setLevel("1");
                    b.setShotcontent(bean.getMsgcontent());
                    b.setCreatetime(DateTools.getSystemTimeLong());
                    b.setUpdatetime(DateTools.getSystemTimeLong());
                    b.setStatus(BaseEnums.DataUsingState.USING.getState());
                    b.setType("1");
                    this.sysMsgRpTService.save(b);
                }


            }

        }

        return Response.success(responsedata);
    }


    private String compareLevel(int leafs){
        String level="1";
        List<MemberGradeT>list=this.memberGradeTService.findAll(MemberGradeT.class);
        for(MemberGradeT memberGradeT:list){
            //10
            if(leafs<=memberGradeT.getEnd()&&leafs>=memberGradeT.getStart()){
                System.out.println("等级"+memberGradeT.getLevelname());
                level=memberGradeT.getLevelname()+"";
            }
        }
        return level;
    }



    /**
     * 初始化个人中心
     * @param rq
     * @return
     */
    @RequestMapping(value="/initMemberCenter",method= RequestMethod.POST)
    public ResponseEntity initMemberCenter(@RequestBody YdStatusInfoT rq){
        Map<String,Object> responsedata=new HashMap<>();
        if(StringUtils.isNotBlank(rq.getWxopenid())){
            Criterion criterion= Restrictions.eq("wxopenid",rq.getWxopenid());
            YdStatusInfoT bean=this.ydStatusInfoTSerivce.findOneByCriteria(YdStatusInfoT.class,criterion);
            if(bean!=null){
                responsedata.put("totalbiaoyang",bean.getTotalbiaoyang());
                responsedata.put("totalyuedu",bean.getTotalyuedu());
                responsedata.put("totalleafs",bean.getTotalleafs());
                responsedata.put("totalshare",bean.getTotalshare());
                responsedata.put("totaltrees",bean.getTotalstrees());
                responsedata.put("memberid",bean.getMemberid());
                //查询会员等级
                Criterion criterion1=Restrictions.eq("memberid",bean.getMemberid());
                MemberGradeRpT memberGradeRpT=this.memberGradeRpTService.findOneByCriteria(MemberGradeRpT.class,criterion1);
                if(memberGradeRpT!=null){
                    responsedata.put("currentlevel",memberGradeRpT.getCurrentlevel());//当前等级
                }
                responsedata.put(TagWords.SUCCESS,true);
            }
        }else{
            responsedata.put(TagWords.SUCCESS,false);
        }
        return Response.success(responsedata);
    }

    /**
     * 更新头像和昵称
     * @param rq
     * @return
     */
    @RequestMapping(value="/updateWxMemberInfo",method= RequestMethod.POST)
    public ResponseEntity updateWxMemberInfo(@RequestBody MemberT rq){
        Map<String,Object> responsedata=new HashMap<>();

        if(StringUtils.isNotBlank(rq.getWxopenid())){
            Criterion criterion= Restrictions.eq("wxopenid",rq.getWxopenid());
            MemberT memberT=this.memberTService.findOneByCriteria(MemberT.class,criterion);
            if(memberT!=null){
                memberT.setNick(rq.getNick());
                memberT.setHeadpath(rq.getHeadpath());
                memberT.setSex(rq.getSex());
                memberT.setLanguage(rq.getLanguage());
                memberT.setCity(rq.getCity());
                memberT.setProvince(rq.getProvince());
                memberT.setCountry(rq.getCountry());
                memberT.setUpdatetime(DateTools.getSystemTimeLong());
                memberT.setVersiont(memberT.getVersiont()+1);

                this.memberTService.update(memberT);

                //初始化会员等级信息
                initMemberGrade(memberT);
                //初始化阅读状态
                initYdStatus(memberT);
                //初始化小树状态
                initSmallTree(memberT);
                responsedata.put(TagWords.SUCCESS,true);
            }
        }else{
            responsedata.put(TagWords.SUCCESS,false);
            responsedata.put(TagWords.MSG,WarnWrods.ERROR_PARAMS);
        }
        return Response.success(responsedata);
    }

    public void initMemberGrade(MemberT rq){
        Criterion criterion=Restrictions.eq("memberid",rq.getId());
        MemberGradeRpT bean=this.memberGradeRpTService.findOneByCriteria(MemberGradeRpT.class,criterion);
        if(bean==null){
            bean=new MemberGradeRpT();
            bean.setId(PrimaryKey.get().toString());
            bean.setMemberid(rq.getId());
            bean.setMembergradeid(StaticKey.EMPTY);
            bean.setCurrentlevel(1);
            bean.setCreatetime(DateTools.getSystemTimeLong());
            bean.setUpdatetime(DateTools.getSystemTimeLong());
            bean.setVersiont(1);
            bean.setStatus(BaseEnums.DataUsingState.USING.getState());
            this.memberGradeRpTService.save(bean);
        }
    }

    /**
     * 初始化阅读数据
     * @param rq
     */
    public void initYdStatus(MemberT rq){
        Criterion criterion=Restrictions.eq("memberid",rq.getId());
        YdStatusInfoT bean=this.ydStatusInfoTSerivce.findOneByCriteria(YdStatusInfoT.class,criterion);
        if(bean==null){
            bean=new YdStatusInfoT();
            bean.setId(PrimaryKey.get().toString());
            bean.setTotalbiaoyang(0);
            bean.setStatus(BaseEnums.DataUsingState.USING.getState());
            bean.setCreatetime(DateTools.getSystemTimeLong());
            bean.setCreatorid("0");
            bean.setUpdatetime(DateTools.getSystemTimeLong());
            bean.setVersiont(1);
            bean.setTotalyuedu(0);
            bean.setTotalleafs(0);
            bean.setTotalshare(0);
            bean.setTotalstrees(0);
            bean.setWxopenid(rq.getWxopenid());
            bean.setMemberid(rq.getId());
            bean.setNextydper(1);
            this.ydStatusInfoTSerivce.save(bean);
        }
    }

    public void initSmallTree(MemberT rq){
        //iscurrentgrow=0表示当前没有正在生长的小树
        Criterion criterion=Restrictions.and(Restrictions.eq("iscurrentgrow",1)).add(Restrictions.eq("memberid",rq.getId()));
        YdTreeInfoT bean=this.ydTreeInfoTService.findOneByCriteria(YdTreeInfoT.class,criterion);
        if(bean==null){
            bean=new YdTreeInfoT();
            bean.setId(PrimaryKey.get().toString());
            bean.setCurrentleafs(0);
            bean.setStatus(BaseEnums.DataUsingState.USING.getState());
            bean.setCreatetime(DateTools.getSystemTimeLong());
            bean.setCreatorid("0");
            bean.setUpdatetime(DateTools.getSystemTimeLong());
            bean.setVersiont(1);
            bean.setNeedleafs(1000);
            bean.setIscurrentgrow(1);
            bean.setPergrow(10);
            bean.setCurrentgrowstatus(1);
            bean.setWxopenid(rq.getWxopenid());
            bean.setMemberid(rq.getId());
            this.ydTreeInfoTService.save(bean);
        }

    }

}
